package com.jingwee.springbootkafka.producer;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;

/**
 * @author jingwei
 * @version 1.0
 * @description
 * @date 2023/8/8
 */
@Component
@Slf4j
public class KafkaBaseProducer {
    @Resource
    private KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * 发送文字消息
     *
     * @param message
     * @return
     */
    public String sendStr(String topicName, String message) {
        ListenableFuture<SendResult<String, Object>> send = kafkaTemplate.send(topicName, message);
        log.info("发送消息，消息是 ===>>> {}", message);
        return message;
    }

    /**
     * 发送对象消息
     *
     * @param obj
     * @return
     */
    public String sendObj(String topicName, Object obj) {
        String message = JSON.toJSONString(obj);
        kafkaTemplate.send(topicName, message);
        return message;
    }
}
